package com.raven.craft.code.generator.mysql.repo.entity;

import com.raven.craft.code.generator.common.constant.JavaType;
import com.raven.craft.code.generator.common.constant.KeyType;
import com.raven.craft.code.generator.common.constant.Nullable;
import com.raven.craft.code.generator.common.constant.SqlType;
import com.raven.craft.code.generator.common.util.EnumUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

/**
 * @author raven
 * @date 2019-03-22 19:03
 */
@Getter
@Setter
@ToString
public class Column {

    private String field;
    private String columnType;
    private String collation;
    private Nullable nullable;
    private KeyType keyType;
    private String defaultValue;
    private String extra;
    private String privileges;
    private String comment;

    private Boolean isPK;
    private SqlType sqlType;
    private JavaType javaType;

    public Boolean getIsPK() {
        return keyType.isPK();
    }

    public SqlType getSimpleSqlType() {
        if (null == sqlType) {
            String[] split = columnType.split("\\(|,|\\)");
            sqlType = EnumUtil.getByCode(SqlType.class, split[0].trim());
        }
        return sqlType;
    }

    public JavaType getJavaType() {
        if (javaType == null) {
            javaType = getJavaTypeByColumnType(columnType);
        }
        return javaType;
    }

    private JavaType getJavaTypeByColumnType(String columnType) {
        String[] split = columnType.split("\\(|,|\\)");
        SqlType sqlType = EnumUtil.getByCode(SqlType.class, split[0].trim());
        Integer intergralLength = null;
        Integer fractionalLength = null;
        if (split.length > 1) {
            intergralLength = Integer.valueOf(split[1].trim());
        }
        if (split.length > 2 && !split[2].trim().equals("unsigned")) {
            fractionalLength = Integer.valueOf(split[2].trim());
        }
        return sqlType.toJavaType(intergralLength, fractionalLength);
    }

    public String getComment() {
        return comment == null ? null : comment.replaceAll("\n", "").replaceAll("\\(", " ").replaceAll("\\)", "");
    }

    public void setComment(String comment) {
        this.comment = comment == null ? null : comment.replaceAll("\n|\r", "");
    }
}
